package com.freight.tws.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.freight.common.core.constant.CacheConstants;
import com.freight.common.core.constant.Constants;
import com.freight.common.core.utils.ServletUtils;
import com.freight.common.core.utils.StringUtils;
import com.freight.common.security.utils.SecurityUtils;
import com.freight.message.api.utils.MsgAsyncUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.freight.common.core.web.controller.BaseServiceImpl;
import com.freight.tws.mapper.TwsNoticeMapper;
import com.freight.tws.domain.TwsNotice;
import com.freight.tws.service.ITwsNoticeService;

import java.util.Date;

/**
 * 公告消息Service业务层处理
 *
 * @author ruoyi
 * @date 2023-01-24
 */
@Service
public class TwsNoticeServiceImpl extends BaseServiceImpl<TwsNoticeMapper, TwsNotice> implements ITwsNoticeService {

    @Autowired
    private TwsNoticeMapper twsNoticeMapper;

    @Autowired
    private MsgAsyncUtil msgAsyncUtil;

    /**
     * 保存新的业务消息并通过websocket通知用户
     * @param userName  登陆用户名
     * @param type  消息类型
     * @param content   消息内容
     */
    @Override
    public void newTwsNotice(String userName, String type, String content) {
        TwsNotice twsNotice = new TwsNotice();
        twsNotice.setNoticeTo(userName);
        twsNotice.setType(type);
        twsNotice.setContent(content);
        twsNotice.setState("0");    // 未读
        if(ServletUtils.getRequest() == null) {
            twsNotice.setCreateBy("0");
            twsNotice.setCreateTime(new Date());
            twsNotice.setDelFlag(Constants.DB_NOT_DELETED);
            twsNoticeMapper.insert(twsNotice);
        } else {
            this.save(twsNotice);
        }
        // 异步通知用户
        msgAsyncUtil.sendWsToOneBusiness(userName);
    }

    /**
     * 消息已读
     * @param id
     * @return
     */
    @Override
    public boolean read(Long id) {
        return this.update(new LambdaUpdateWrapper<TwsNotice>()
                .set(TwsNotice::getState, "1")
                .eq(TwsNotice::getId, id));
    }

    /**
     * 全部已读
     * @return
     */
    @Override
    public boolean reads() {
        return this.update(new LambdaUpdateWrapper<TwsNotice>()
                .set(TwsNotice::getState, "1")
                .eq(TwsNotice::getNoticeTo, SecurityUtils.getUsername()));
    }

}
